import json

from common.config.database import Base
from common.utils.common_util import SqlalchemyUtil
from common.utils.validate_util import ValidateUtil


class DictUtil:
    @staticmethod
    def model_to_dict(model):
        """Convert SQLAlchemy model instance to dictionary."""
        return {c.name: getattr(model, c.name) for c in model.__table__.columns}


    #判断是否为null---查询对象
    @staticmethod
    def tuple_to_dict(res):
        res=res.fetchone()
        if ValidateUtil.is_not_empty(res):
            if all(item is None for item in res):
                return None
            result_dict = res._asdict()
            # 自动检测并转换JSON字符串
            for key, value in result_dict.items():
                if isinstance(value, str) and (value.startswith('[') or value.startswith('{')):
                    try:
                        result_dict[key] = json.loads(value)
                    except json.JSONDecodeError:
                        # 如果转换失败，保留原始值
                        pass
            return result_dict
        return None

    #判断是否为空的列表---查询list列表数据
    @staticmethod
    def list_to_dict(res):
        res=res.fetchall()
        if ValidateUtil.is_not_empty(res):
            if all(all(item is None for item in row) for row in res):
                return None
            result_list = []
            for item in res:
                result_dict = item._asdict()
                # 自动检测并转换JSON字符串
                for key, value in result_dict.items():
                    if isinstance(value, str) and (value.startswith('[') or value.startswith('{')):
                        try:
                            result_dict[key] = json.loads(value)
                        except json.JSONDecodeError:
                            # 如果转换失败，保留原始值
                            pass
                result_list.append(result_dict)
            return result_list
        return None
    @staticmethod
    def reslist_to_dict(res):
        if ValidateUtil.is_not_empty(res):
            return [item._asdict() for item in res]
        return None

    @staticmethod
    def list_to_dict_gaoji(res):
        res = res.unique()
        if ValidateUtil.is_not_empty(res):
            return [zhuanhuan(item) for item in res]
        return None

    @staticmethod
    def tuple_to_dict_gaoji(res):
        res = res.unique()
        res = res.fetchone()
        if ValidateUtil.is_not_empty(res):
            return zhuanhuan(res)
        return None
def zhuanhuan(res):
    if all([isinstance(row, Base) for row in res]):
        for row in res:
            return SqlalchemyUtil.base_to_dict(row)
